package com.joesem.sale.client.logic.workOrder

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.jiaxing.sale.client.databinding.ActivityCreateCustomerBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.option.optionArea
import com.joesem.sale.client.network.data.CustomerUserMode
import com.joesem.sale.client.utils.activityResult.launcherResult
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.*


class CreateCustomerActivity : BaseActivity<ActivityCreateCustomerBinding>() {

    private val viewModel by createViewModel<CustomerViewModel>()

    private val values = hashMapOf<String, Any?>()

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = "创建客户"
    }

    override fun ActivityCreateCustomerBinding.initView(savedInstanceState: Bundle?) {
        values["status"] = 0
        intent.getIntExtra("eventId", -1).let {
            if (it > 0) {
                values["event_id"] = it
            }
        }
    }

    override fun ActivityCreateCustomerBinding.initIntent(intent: Any?) {
        when (intent) {
            is CustomerViewModel.CreateIntent -> {
                setResult(Activity.RESULT_OK, Intent().apply {
                    putExtra("data", intent.date)
                })
                finish()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun ActivityCreateCustomerBinding.initListener() {
        edCustomerName.addTextChangedListener {
            values["name"] = it?.toString()
        }
        etCustomerShort.addTextChangedListener {
            values["short_name"] = it?.toString()
        }
        btnCustomerType.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择客户类型", type = TYPE_TYPES
            ) { name, code ->
                values["entry_type_name"] = code
                tvCustomerType.text = name
            }
        }
        btnAddress.click {
            optionArea(supportFragmentManager) { province, city, county ->
                values["province_id"] = province?.id
                values["city_id"] = city?.id
                values["county_id"] = county?.id
                tvAddress.text = province?.name + city?.name + county?.name
            }
        }
        etAddressDetails.addTextChangedListener {
            values["address"] = it?.toString()
        }
        btnIndustry.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择所属行业", type = TYPE_INDUSTRIES
            ) { name, code ->
                values["industry_name"] = code
                tvIndustry.text = name
            }
        }
        btnProperties.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择客户性质", type = TYPE_PROPERTIES
            ) { name, code ->
                values["customer_type_name"] = code
                tvProperties.text = name
            }
        }
        btnNetworkPoint.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择服务网点", type = TYPE_NETWORK_POINT
            ) { name, code ->
                values["department_id"] = code
                tvNetworkPoint.text = name
            }
        }
        btnCustomerTable.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择客户标签", type = TYPE_TAGS
            ) { name, code ->
                values["tag_name"] = code
                tvCustomerTable.text = name
            }
        }
        btnLevels.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择安全等级", type = TYPE_LEVELS
            ) { name, code ->
                values["safe_level"] = code
                tvLevels.text = name
            }
        }
        btnSources.click {
            optionCustomerParams(
                fm = supportFragmentManager, title = "选择客户来源", type = TYPE_SOURCES
            ) { name, code ->
                values["source"] = code
                tvSources.text = name
            }
        }
        btnResponsiblePerson.click {
            optionDeptUser(this@CreateCustomerActivity, "选择负责人") {
                values["owner_id"] = it.id
                tvResponsiblePerson.text = it.realname.orEmpty()
            }
        }
        btnDate.click {
            optionDatePickerSingle(it.context) {
                values["contact_at"] = it
                tvDate.text = it
            }
        }
        btnConfirm.click {
            viewModel.confirm(values)
        }
    }

}

class CustomerViewModel(application: Application) : BaseViewModel(application) {
    fun confirm(values: HashMap<String, Any?>) {
        if (checkValue(values)) {
            request(isLoading = true, request = {
                createCustomer(values)
            }, response = {
                toast(it.msg)
                it.data?.let {
                    actionIntent(CreateIntent(it))
                }
            }, responseFailed = {
                toast(it.message)
            })
        }
    }

    private fun checkValue(values: HashMap<String, Any?>): Boolean {
        if (values["name"]?.toString().isNullOrEmpty()) {
            toast("请输入客户名称")
            return false
        }
        if (values["short_name"]?.toString().isNullOrEmpty()) {
            toast("请输入客户简称")
            return false
        }
        if (values["entry_type_name"] == null) {
            toast("请选择客户类型")
            return false
        }
        if (values["province_id"] == null || values["city_id"] == null || values["county_id"] == null) {
            toast("请选择省市区")
            return false
        }
        if (values["address"]?.toString().isNullOrEmpty()) {
            toast("请输入地址详细")
            return false
        }
        if (values["industry_name"] == null) {
            toast("请选择所属行业")
            return false
        }
        if (values["customer_type_name"] == null) {
            toast("请选择客户性质")
            return false
        }
        if (values["department_id"] == null) {
            toast("请选择服务网点")
            return false
        }
        if (values["tag_name"] == null) {
            toast("请选择客户标签")
            return false
        }
        if (values["safe_level"] == null) {
            toast("请选择安全等级")
            return false
        }
        if (values["source"] == null) {
            toast("请选择客户来源")
            return false
        }
        if (values["owner_id"] == null) {
            toast("请选择负责人")
            return false
        }
        if (values["contact_at"] == null) {
            toast("请选择签约日期")
            return false
        }
        return true
    }

    class CreateIntent(val date: CustomerUserMode)
}

fun optionCreateCustomer(
    activity: AppCompatActivity,
    eventId: Int? = null,
    result: (CustomerUserMode) -> Unit
) {
    activity.launcherResult<CreateCustomerActivity>("eventId" to eventId) { _: Int, data: Intent? ->
        data?.let { it.getParcelableExtra<CustomerUserMode>("data")?.let(result) }
    }
}